package com.cloudeasy.user.controller.admin;

import com.cloudeasy.api.util.ResultUtil;
import com.cloudeasy.api.vo.Result;
import com.cloudeasy.api.vo.user.UserRoleVO;
import com.cloudeasy.user.po.Role;
import com.cloudeasy.user.po.UserRole;
import com.cloudeasy.user.service.RoleService;
import com.cloudeasy.user.service.expand.VerifyPermissionService;
import com.cloudeasy.user.util.UserRoleUtil;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
public class VerifyPermissionController {
    private final RoleService roleService;

    private final VerifyPermissionService verifyPermissionService;

    public VerifyPermissionController(RoleService roleService, VerifyPermissionService verifyPermissionService) {
        this.roleService = roleService;
        this.verifyPermissionService = verifyPermissionService;
    }

    /**
     * 验证是否有权限操作
     *
     * @param permissionId  权限Id
     * @param targetAreas   目标操作区域
     * @param operateUserId 操作用户Id
     * @return {@link Result<Boolean>}
     */
    @PostMapping("/can_do/{permissionId}/{operateUserId}")
    public Result<Boolean> canDo(@PathVariable("permissionId") String permissionId,
                                 @RequestParam("targetAreas") List<String> targetAreas,
                                 @PathVariable("operateUserId") String operateUserId) {
        return ResultUtil.success(verifyPermissionService.canDo(permissionId, targetAreas, operateUserId));
    }

    /**
     * 获取用户可以操作的用户角色信息
     *
     * @param permissionId  权限Id
     * @param operateUserId 操作用户Id
     * @return {@link List<UserRoleVO>}的{@link Result}
     */
    @PostMapping("/operate_area/{permissionId}/{operateUserId}")
    public Result<List<UserRoleVO>> operateArea(@PathVariable("permissionId") String permissionId,
                                                @PathVariable("operateUserId") String operateUserId) {
        List<UserRole> userRoles = verifyPermissionService.getPossessPermissionRolesByUserId(permissionId, operateUserId);
        List<String> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<Role> roles = new ArrayList<>();
        if (roleIds.size() > 0) {
            roles.addAll(roleService.list(roleIds));
        }
        return ResultUtil.success(UserRoleUtil.convert(userRoles, roles));
    }
}
